package jgl.vajra.management.widget.retrofithelper.interceptor;

import jgl.vajra.management.widget.utils.CommonUtils;
import jgl.vajra.management.widget.retrofithelper.rxexception.HttpNativeException;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by Mloong on 2018/7/31.
 */

public class HttpNativeStatusInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());

        int code = response.code();
        if (code >= 400) {
            if ( !CommonUtils.bodyEncoded(response.headers())) {
                ResponseBody responseBody = response.body();
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();

                Charset charset = NetworkInterceptor.UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(NetworkInterceptor.UTF8);
                }

                if (!CommonUtils.isPlaintext(buffer)) {
                    return response;
                }
                long contentLength = responseBody.contentLength();
                if (contentLength != 0) {
                    String readString = buffer.clone().readString(charset).trim();
                    // throw new TokenInvalidException();
                    String message = "";
                    try {
                        message = response.message();
                    } catch (Exception e) {
                        message = "";
                        code = 10086;
                    } finally {
                        throw new HttpNativeException(code, message, readString);
                    }
                }

            }

        }
        return response;
    }
}
